//
//  ENADViewController.m
//  EverydayNews
//
//  Created by 李沛池 on 2017/8/6.
//  Copyright © 2017年 Godlike. All rights reserved.
//

#import "ENADViewController.h"
#import <UIImageView+WebCache.h>
#import "ENInterface.h"
#import "LPCNotificationManager.h"

@interface ENADViewController ()

@property (weak, nonatomic) IBOutlet UIImageView *iView;
@property (weak, nonatomic) IBOutlet UIButton *btnPass;

@end

@implementation ENADViewController
{
    NSTimer *_timer;
    int _timeLine;////广告显示倒计时 5秒 可跳过默认页面显示倒计时 3秒  AD请求2秒超时
    NSString *_strURL;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.

    [self requestADInfo];
    
}

- (void)initData
{
    _timeLine = 3;
    _timer = [NSTimer scheduledTimerWithTimeInterval:1.0f repeats:YES block:^(NSTimer * _Nonnull timer) {
        [self reduceTime];
    }];
}

- (void)initUI
{
    [_btnPass.layer setBorderColor:COLOR_FFFFFF(0xe8e8e8).CGColor];
    [_btnPass.layer setBorderWidth:0.5];
    [_btnPass.layer setMasksToBounds:YES];
    [_btnPass.layer setCornerRadius:15];
}

- (void)requestADInfo
{
    [ENInterface loadADWithPageNum:arc4random()%3 block:^(NSDictionary *dic, NSError *error) {
        [_iView sd_setImageWithURL:[NSURL URLWithString:dic[@"imageUrl"]] placeholderImage:ImageWithContentsOfFileDefault(@"ad_default")];
        _strURL = dic[@"content"];
    }];
}

-(void)reduceTime
{
    _timeLine--;
    [_btnPass setTitle:[NSString stringWithFormat:@"跳过(%d)",_timeLine] forState:UIControlStateNormal];
    if (_timeLine == 0) {
        [self stopTime];
        [self dissmiss];
    }
}

-(void)stopTime
{
    [_timer invalidate];
    _timer=nil;
}

- (IBAction)passAction:(UIButton *)sender
{
    if (_timer!=nil) {
        [self stopTime];
    }
    [self dissmiss];
}

//跳转到广告
- (IBAction)pusthToAd:(UITapGestureRecognizer *)sender
{
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:_strURL]];
}

- (void)dissmiss
{
    [self dismissViewControllerAnimated:NO completion:nil];
    [[LPCNotificationManager sharedLPCNotificationManager] postNotification:LPCNotificationType_doneLaunchAD obj:nil userInfo:nil];
}

@end
